package org.ftc.service;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.ftc.dao.SessionDao;
import org.ftc.domain.Session;
import org.ftc.form.SessionForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class SessionService {

	@Autowired
	SessionDao sessionDao;

	public Session load(String id) {
		return sessionDao.load(id);
	}

	public Session get(String id) {
		return sessionDao.get(id);
	}

	public synchronized boolean save(Session entity) {
		Authentication userDetails = SecurityContextHolder.getContext().getAuthentication();
		if (userDetails != null)
			entity.setCreationUser(userDetails.getName());
		entity.setCreationDate(new Date());
		return sessionDao.save(entity);
	}

	public synchronized boolean saveOrUpdate(Session entity) {
		return sessionDao.saveOrUpdate(entity);
	}

	public synchronized boolean update(Session entity) {
		entity.setModifyDate(new Date());
		entity.setModifyUser(SecurityContextHolder.getContext().getAuthentication().getName());
		return sessionDao.update(entity);

	}

	public synchronized boolean delete(Session entity) {
		return sessionDao.delete(entity);
	}

	public synchronized boolean delete(String id) {
		return sessionDao.delete(id);
	}

	public List<Session> findPage(int offset, int pageSize) {
		return sessionDao.findPage(offset, pageSize);
	}

	public List<Session> findAll() {
		return sessionDao.findAll();
	}

	public long countAll() {
		return sessionDao.countAll();
	}

	public List<Session> findPage(SessionForm form, int offset, int pageSize) {
		return sessionDao.findPage(form, offset, pageSize);
	}

	public long count(SessionForm form) {
		return sessionDao.count(form);
	}
	
	public Session findNext(Session session) {
		return sessionDao.findNext(session);
	}
	
	public List<Session> findSessions(String sessionNo) {
		Session session = this.get(sessionNo);
		 List<Session> list = sessionDao.findSessions(session);
		 Collections.sort(list, new Comparator<Session>(){
			@Override
			public int compare(Session o1, Session o2) {
				if(o1.getMeetingDate().before(o2.getMeetingDate())){
					return 1;
				}else if(o1.getMeetingDate().after(o2.getMeetingDate())){
					return -1;
				}else{
					return 0;
				}
			}
		 });
		 return list;
	}

}
